<?php

class Traderefund extends CS_Controller
{
    protected $status = array('1' => '申请退款', 2 => '退款成功', 3 => '退款失败');

    public function _init()
    {
        $this->load->library('pagination');
        $this->load->library('swiftpass/swiftpay', null, 'swiftpay');
        $this->load->model('trade_refund_model', 'trade_refund');
        $this->load->model('user_transfer_charge_model', 'user_transfer_charge');
    }

    public function index($pg = 1)
    {
        $getData = $this->input->get();
        $page_num = 20;
        $num = ($pg-1)*$page_num;
        $config['base_url'] = base_url('traderefund/index');
        $config['total_rows'] = $this->trade_refund->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list'] = $this->pagination->create_links();
        $data['page_list'] = $this->trade_refund->page_list($getData, $page_num, $num);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['status'] = $this->status;
        $this->load->view('traderefund/index', $data);
    }

    public function refund($id)
    {
        $result = $this->trade_refund->findById($id);

        if ($result->num_rows() == 0) {
            $this->error('traderefund/index', null, '参数错误');
        }
        $result = $result->row();

        //查找支付通的商户号 和秘钥
        $swiftParam = $this->user_transfer_charge->findBySid($result->sid);
        if ($swiftParam->num_rows() == 0) {
            $this->error('traderefund/index?refund_id='. $result->refund_id, null, '编号('.$result->sid.')的景区未绑定兴业银行参数');
        }
        $swiftParam = $swiftParam->row();

        $request = array(
            'service'        => 'unified.trade.refund',
            'out_trade_no'   => $result->pay_id,
            'transaction_id' => $result->transaction_id,
            'out_refund_no'  => $result->refund_id,
            'total_fee'      => ($result->total_fee * 100),
            'refund_fee'     => ($result->refund_fee * 100),
            'mch_id'         => $swiftParam->mch_id,
            'op_user_id'     => $swiftParam->mch_id,
            'refund_channel' => 'ORIGINAL'
        );
        $response = $this->swiftpay->submit($request, $swiftParam->key);
        $data['message'] = '';
        if ($response) {
            $data['status'] = 1; //退款成功
        } else {
            $data['status'] = 2; //退款失败
            $data['message'] = $this->swiftpay->getError();
        }
        $this->trade_refund->updatePartById($result->id, $data);

        if ($data['status'] == 1) {
            $this->success('traderefund/index?refund_id='. $result->refund_id, null, '退款成功');
        } else {
            $this->error('traderefund/index?refund_id='. $result->refund_id, null, $data['message']);
        }
    }
}